package advertising

import (
	"context"
	"strings"

	"advertising/config/mysql"
	"advertising/internal/app/grpc/client"
	"advertising/internal/app/grpc/protoc/advertisingc"
	"advertising/internal/app/grpc/protoc/mini_app"
	"advertising/internal/app/web/service"
	"advertising/internal/dao"
	"advertising/internal/define"
	"advertising/internal/models"

	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"github.com/samber/lo"
)

// ScheduleSave 投放计划新增保存
func (s *Server) ScheduleSave(ctx context.Context, req *advertisingc.SPublishScheduleSaveReq) (*advertisingc.SPublishScheduleSaveRsp, error) {
	res := &advertisingc.SPublishScheduleSaveRsp{}

	// 参数验证
	if req.Position == 0 {
		res.Code = -1
		res.Msg = "投放位置不能为空"
		return res, nil
	}

	if req.Position != 1 && req.Position != 2 && req.Position != 3 {
		res.Code = -1
		res.Msg = "投放位置错误"
		return res, nil
	}

	if req.Name == "" {
		res.Code = -1
		res.Msg = "计划名称不能为空"
		return res, nil
	}

	if req.StartTime == 0 {
		res.Code = -1
		res.Msg = "投放周期开始时间不能为空"
		return res, nil
	}

	if req.EndTime == 0 {
		res.Code = -1
		res.Msg = "投放周期结束时间不能为空"
		return res, nil
	}

	if req.EndTime <= req.StartTime {
		res.Code = -1
		res.Msg = "投放周期结束时间不能小于开始时间"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	// 转换材料数据
	materials := make([]struct {
		MaterialID      string `json:"material_id"`
		Duration        int64  `json:"duration"`
		PlayType        int8   `json:"play_type"`
		RegularInterval int64  `json:"regular_interval"`
	}, 0)

	for _, material := range req.Materials {
		materials = append(materials, struct {
			MaterialID      string `json:"material_id"`
			Duration        int64  `json:"duration"`
			PlayType        int8   `json:"play_type"`
			RegularInterval int64  `json:"regular_interval"`
		}{
			MaterialID:      material.MaterialId,
			Duration:        material.Duration,
			PlayType:        int8(material.PlayType),
			RegularInterval: material.RegularInterval,
		})
	}

	db := mysql.NewDB()
	id, timeoutRemind, err := service.PublishSchedule{}.SaveNoAuth(
		ctx,
		db,
		req.MerchantId,
		req.MerchantName,
		req.UserId,
		req.Username,
		req.Id,
		int8(req.Position),
		req.Name,
		req.StartTime,
		req.EndTime,
		req.Details,
		materials,
		req.Gender,
		req.Age,
		req.Tag,
		req.Devices,
		int8(req.PublishType),
		int8(req.DetailsShow),
		req.PublishCount,
		req.SupportActivityId,
	)

	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "保存成功"
	res.TimeoutRemind = timeoutRemind != 0
	res.Id = id
	return res, nil
}

// ScheduleList 投放计划列表
func (s *Server) ScheduleList(ctx context.Context, req *advertisingc.SPublishScheduleListReq) (*advertisingc.SPublishScheduleListRsp, error) {
	res := &advertisingc.SPublishScheduleListRsp{}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	// db := mysql.NewDB()
	data, total, count, err := service.PublishSchedule{}.List(ctx, req.MerchantId, req.MerchantPath, req.Name,
		int(req.Position), int(req.Status), req.StartTime, req.EndTime, req.LocationId, req.DistrictId,
		req.Devices, int(req.Page), int(req.Limit), int(req.Platform), req.AmountThresh)

	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleListRsp_SPublishScheduleListData{
		Count: count,
		Total: total.Total,
		List:  make([]*advertisingc.SPublishScheduleListRsp_SPublishScheduleListData_SPublishScheduleItem, 0),
	}

	// 转换数据
	for _, item := range data {
		materials := make([]*advertisingc.SPublishScheduleListRsp_SPublishScheduleListData_SPublishScheduleItem_Materials, 0)
		for _, material := range item.Materials {
			materials = append(materials, &advertisingc.SPublishScheduleListRsp_SPublishScheduleListData_SPublishScheduleItem_Materials{
				MaterialId: material.MaterialID,
				FilePath:   material.FilePath,
				// Name:            material.Name,
				Type:        int32(material.Type),
				Duration:    material.Duration,
				RepeatTimes: material.RepeatTimes,
				// PlayType:        int32(material.PlayType),
				// RegularInterval: int32(material.RegularInterval),
			})
		}

		res.Data.List = append(res.Data.List, &advertisingc.SPublishScheduleListRsp_SPublishScheduleListData_SPublishScheduleItem{
			Id:             item.ID,
			Name:           item.Name,
			Position:       int32(item.Position),
			PublishType:    int32(item.PublishType),
			PublishCount:   item.PublishCount,
			StartTime:      item.StartTime,
			EndTime:        item.EndTime,
			Duration:       item.Duration,
			Details:        item.Details,
			Status:         int32(item.Status),
			DistrictId:     item.DistrictID,
			LocationId:     item.LocationID,
			Gender:         item.Gender,
			Age:            item.Age,
			Tag:            item.Tag,
			MerchantId:     item.MerchantID,
			MerchantName:   item.MerchantName,
			CreateUser:     item.CreateUser,
			CreateUsername: item.CreateUserName,
			CreatedAt:      item.CreatedAt,
			DeletedAt:      item.DeletedAt,
			Devices:        item.Devices,
			Materials:      materials,
			DetailsShow:    int32(item.DetailsShow),
			// DeviceLocation: item.DeviceLocation,
		})
	}

	return res, nil
}

// ScheduleDetail 投放计划详情
func (s *Server) ScheduleDetail(ctx context.Context, req *advertisingc.SPublishScheduleDetailReq) (*advertisingc.SPublishScheduleDetailRsp, error) {
	res := &advertisingc.SPublishScheduleDetailRsp{}

	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	data, err := service.PublishSchedule{}.Detail(ctx, req.MerchantId, req.Id)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleDetailRsp_SPublishScheduleDetail{
		Id:             data.ID,
		Name:           data.Name,
		Position:       int32(data.Position),
		PublishType:    int32(data.PublishType),
		PublishCount:   data.PublishCount,
		StartTime:      data.StartTime,
		EndTime:        data.EndTime,
		Duration:       data.Duration,
		Details:        data.Details,
		Status:         int32(data.Status),
		DistrictId:     data.DistrictID,
		LocationId:     data.LocationID,
		Gender:         data.Gender,
		Age:            data.Age,
		Tag:            data.Tag,
		MerchantId:     data.MerchantID,
		MerchantName:   data.MerchantName,
		CreateUser:     data.CreateUser,
		CreateUsername: data.CreateUserName,
		CreatedAt:      data.CreatedAt,
		DeletedAt:      data.DeletedAt,
		Devices:        data.Devices,
		DetailsShow:    int32(data.DetailsShow),
	}

	// 转换材料数据
	for _, material := range data.Materials {
		res.Data.Materials = append(res.Data.Materials, &advertisingc.SPublishScheduleDetailRsp_SPublishScheduleDetail_Materials{
			MaterialId:      material.MaterialID,
			FilePath:        material.FilePath,
			Name:            material.Name,
			Type:            int32(material.Type),
			Duration:        material.Duration,
			RepeatTimes:     material.RepeatTimes,
			PlayType:        material.PlayType,
			RegularInterval: material.RegularInterval,
		})
	}

	return res, nil
}

// ScheduleSimpleDetail 投放计划简单详情
func (s *Server) ScheduleSimpleDetail(ctx context.Context, req *advertisingc.SPublishScheduleSimpleDetailReq) (*advertisingc.SPublishScheduleSimpleDetailRsp, error) {
	res := &advertisingc.SPublishScheduleSimpleDetailRsp{}

	if req.ScheduleId == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	data, err := service.PublishSchedule{}.SimpleDetail(ctx, req.ScheduleId)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleSimpleDetailRsp_SPublishScheduleSimpleDetail{
		Id:   data.ID,
		Name: data.Name,
		// Details: data.Details,
	}

	return res, nil
}

// ScheduleSubmit 投放计划提交审核
func (s *Server) ScheduleSubmit(ctx context.Context, req *advertisingc.SPublishScheduleSubmitReq) (*advertisingc.SPublishScheduleSubmitRsp, error) {
	res := &advertisingc.SPublishScheduleSubmitRsp{}

	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	err := service.PublishSchedule{}.Submit(ctx, db, req.MerchantId, req.Id)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "提交成功"
	return res, nil
}

// ScheduleSubmit 投放计划状态改变
func (s *Server) ScheduleChangeStatus(ctx context.Context, req *advertisingc.SPublishScheduleChangeStatusReq) (*advertisingc.SPublishScheduleChangeStatusRsp, error) {
	res := &advertisingc.SPublishScheduleChangeStatusRsp{}

	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	err := service.PublishSchedule{}.ChangeSatatus(ctx, db, req.MerchantId, req.Id, int8(req.Status))
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "提交成功"
	return res, nil
}

// ScheduleSubmit 投放计划设置订单ID
func (s *Server) ScheduleSetOrderID(ctx context.Context, req *advertisingc.SPublishScheduleSetOrderIDReq) (*advertisingc.SPublishScheduleSetOrderIDRsp, error) {
	res := &advertisingc.SPublishScheduleSetOrderIDRsp{}

	logx.Info(context.Background(), "Advertising schedule_rpc ScheduleSetOrderID", logx.Any("req", req))
	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	err := service.PublishSchedule{}.SetOrderID(ctx, db, req.Id, req.OrderId, req.PayAmount, req.PaidAmount, req.DiscountAmount, req.CustomName, req.PhoneNumber, req.OutTradeNo)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "提交成功"
	return res, nil
}

// End 投放计划终止
func (s *Server) End(ctx context.Context, req *advertisingc.SPublishScheduleEndReq) (*advertisingc.SPublishScheduleEndRsp, error) {
	res := &advertisingc.SPublishScheduleEndRsp{}

	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	err := service.PublishSchedule{}.End(ctx, db, req.MerchantId, req.Id)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "终止成功"
	return res, nil
}

// AuditingPublishScheduleCount 审核中计划统计
func (s *Server) AuditingPublishScheduleCount(ctx context.Context, req *advertisingc.SAuditingPublishScheduleCountReq) (*advertisingc.SAuditingPublishScheduleCountRsp, error) {
	res := &advertisingc.SAuditingPublishScheduleCountRsp{}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	count, err := service.PublishSchedule{}.AuditingPublishScheduleCount(ctx, db, req.MerchantId)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Count = int32(count)
	return res, nil
}

// PublishingPublishScheduleCount 投放中计划统计
func (s *Server) PublishingPublishScheduleCount(ctx context.Context, req *advertisingc.SPublishingPublishScheduleCountReq) (*advertisingc.SPublishingPublishScheduleCountRsp, error) {
	res := &advertisingc.SPublishingPublishScheduleCountRsp{}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	count, err := service.PublishSchedule{}.PublishingPublishScheduleCount(ctx, db, req.MerchantId)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Count = int32(count)
	return res, nil
}

// ScheduleCalendar 投放计划日历
func (s *Server) ScheduleCalendar(ctx context.Context, req *advertisingc.SPublishScheduleCalendarReq) (*advertisingc.SPublishScheduleCalendarRsp, error) {
	res := &advertisingc.SPublishScheduleCalendarRsp{}

	// if req.MerchantId == "" {
	// 	res.Code = -1
	// 	res.Msg = "商户ID不能为空"
	// 	return res, nil
	// }

	db := mysql.NewDB()
	data, count, err := service.PublishSchedule{}.ScheduleCalendar(ctx, db, req.MerchantId, req.StartTime, req.EndTime)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleCalendarRsp_SPublishScheduleCalendarData{
		Count: int32(count),
		List:  make([]*advertisingc.SPublishScheduleCalendarRsp_SPublishScheduleCalendarData_SPublishScheduleCalendarItem, 0),
	}

	// 转换数据
	for _, item := range data {
		res.Data.List = append(res.Data.List, &advertisingc.SPublishScheduleCalendarRsp_SPublishScheduleCalendarData_SPublishScheduleCalendarItem{
			Id:        item.ID,
			Name:      item.Name,
			Status:    int32(item.Status),
			StartTime: item.StartTime,
			EndTime:   item.EndTime,
		})
	}

	return res, nil
}

// Test 投放计划测试
func (s *Server) Test(ctx context.Context, req *advertisingc.SPublishScheduleTestReq) (*advertisingc.SPublishScheduleTestRsp, error) {
	res := &advertisingc.SPublishScheduleTestRsp{}

	// 这里调用现有的 GetPublishSchedule 方法
	infoReq := &advertisingc.GetPublishScheduleReq{}
	infoReq.Devices = req.Devices
	infoReq.Force = req.Force

	_, err := s.GetPublishSchedule(ctx, infoReq)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "测试成功"
	res.List = make([]*advertisingc.SPublishScheduleTestRsp_SPublishScheduleTestItem, 0)

	return res, nil
}

// ScheduleListOrderInfo 投放计划列表（含订单信息）
func (s *Server) ScheduleListOrderInfo(ctx context.Context, req *advertisingc.SPublishScheduleListOrderInfoReq) (*advertisingc.SPublishScheduleListOrderInfoRsp, error) {
	res := &advertisingc.SPublishScheduleListOrderInfoRsp{}

	data, total, count, err := service.PublishSchedule{}.ListOrderInfo(
		ctx,
		req.MerchantId, req.MerchantPath, req.Name,
		int(req.Position), int(req.Status),
		req.StartTime, req.EndTime,
		req.LocationId, req.DistrictId,
		req.Devices,
		int(req.Page), int(req.Limit),
		int(req.Platform),
		req.AmountThresh,
		int(req.PayStatus),
		req.CustomName,
		req.PhoneNumber,
		req.OutTradeNo,
		req.SupportActivityId,
		req.CreatedStartTime,
		req.CreatedEndTime,
	)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleListOrderInfoRsp_Data{
		Count: count,
		Total: total.Total,
		List:  make([]*advertisingc.SPublishScheduleListOrderInfoRsp_Data_Item, 0),
	}

	for _, item := range data {
		// materials
		mats := make([]*advertisingc.SPublishScheduleListOrderInfoRsp_Data_Item_Materials, 0, len(item.Materials))
		for _, m := range item.Materials {
			mats = append(mats, &advertisingc.SPublishScheduleListOrderInfoRsp_Data_Item_Materials{
				MaterialId:             m.MaterialID,
				FilePath:               m.FilePath,
				Name:                   m.Name,
				Type:                   int32(m.Type),
				Duration:               m.Duration,
				RepeatTimes:            m.RepeatTimes,
				PlayType:               m.PlayType,
				RegularInterval:        m.RegularInterval,
				DeviceHasMaterialCount: int32(m.DeviceHasMaterialCount),
				DeviceHasMaterial:      m.DeviceHasMaterial,
			})
		}

		platform := 1
		if item.OrderID == "" {
			platform = 1
		} else {
			platform = 2
		}
		// 组装 item
		res.Data.List = append(res.Data.List, &advertisingc.SPublishScheduleListOrderInfoRsp_Data_Item{
			// 基础计划信息
			Id:             item.ID,
			Name:           item.Name,
			Position:       int32(item.Position),
			StartTime:      item.StartTime,
			EndTime:        item.EndTime,
			Duration:       item.Duration,
			Details:        item.Details,
			Status:         int32(item.Status),
			DistrictId:     item.DistrictID,
			LocationId:     item.LocationID,
			MerchantId:     item.MerchantID,
			MerchantName:   item.MerchantName,
			CreateUser:     item.CreateUser,
			CreateUsername: item.CreateUserName,
			CreatedAt:      item.CreatedAt,
			DeletedAt:      item.DeletedAt,
			DeviceCount:    int64(item.DeviceCount),
			Orientation:    int32(item.Orientation),
			PublishType:    int32(item.PublishType),
			Devices:        item.Devices,
			Materials:      mats,
			DetailsShow:    int32(item.DetailsShow),
			// DeviceLocation: item.DeviceLocation,
			PublishCount: item.PublishCount,
			Gender:       item.Gender,
			Age:          item.Age,
			Tag:          item.Tag,

			// 订单扩展信息
			CustomName:      item.CustomName,
			PhoneNumber:     item.PhoneNumber,
			DeviceIds:       item.DeviceIds,
			StartAt:         item.StartAt,
			EndAt:           item.EndAt,
			Remark:          item.Remark,
			Openid:          item.Openid,
			AdvertisementId: item.AdvertisementId,
			PayAmount:       item.PayAmount,
			PaidAmount:      item.PaidAmount,
			PaidId:          item.PaidId,
			DiscountAmount:  item.DiscountAmount,

			// 下发统计
			OrderId:    item.OrderID,
			Platform:   int32(platform),
			PayStatus:  int32(item.PayStatus),
			OutTradeNo: item.PublishSchedule.OutTradeNo,
		})
	}

	return res, nil
}

// ScheduleDetailOrderInfo 投放计划详情（含订单信息）
func (s *Server) ScheduleDetailOrderInfo(ctx context.Context, req *advertisingc.SPublishScheduleDetailOrderInfoReq) (*advertisingc.SPublishScheduleDetailOrderInfoRsp, error) {
	res := &advertisingc.SPublishScheduleDetailOrderInfoRsp{}

	if req.Id == "" {
		res.Code = -1
		res.Msg = "计划ID不能为空"
		return res, nil
	}

	data, err := service.PublishSchedule{}.DetailOrderInfo(ctx, req.MerchantId, req.Id)
	if err != nil {
		res.Code = -1
		res.Msg = err.Error()
		return res, nil
	}

	platform := 1
	if data.OrderID == "" {
		platform = 1
	} else {
		platform = 2
	}
	res.Code = 0
	res.Msg = "获取成功"
	res.Data = &advertisingc.SPublishScheduleDetailOrderInfoRsp_Data{
		// 基础详情
		Id:             data.ID,
		Name:           data.Name,
		Position:       int32(data.Position),
		StartTime:      data.StartTime,
		EndTime:        data.EndTime,
		Duration:       data.Duration,
		Details:        data.Details,
		Status:         int32(data.Status),
		DistrictId:     data.DistrictID,
		LocationId:     data.LocationID,
		MerchantId:     data.MerchantID,
		MerchantName:   data.MerchantName,
		CreateUser:     data.CreateUser,
		CreateUsername: data.CreateUserName,
		CreatedAt:      data.CreatedAt,
		DeletedAt:      data.DeletedAt,
		DeviceCount:    int64(data.DeviceCount),
		Orientation:    int32(data.Orientation),
		PublishType:    int32(data.PublishType),
		Devices:        data.Devices,
		DetailsShow:    int32(data.DetailsShow),
		// DeviceLocation: data.DeviceLocation,
		PublishCount: data.PublishCount,
		Gender:       data.Gender,
		Age:          data.Age,
		Tag:          data.Tag,

		// 订单扩展
		CustomName:      data.CustomName,
		PhoneNumber:     data.PhoneNumber,
		DeviceIds:       data.DeviceIds,
		StartAt:         data.StartAt,
		EndAt:           data.EndAt,
		Remark:          data.Remark,
		Openid:          data.Openid,
		AdvertisementId: data.AdvertisementId,
		PayAmount:       data.PayAmount,
		PaidAmount:      data.PaidAmount,
		PaidId:          data.PaidId,
		DiscountAmount:  data.DiscountAmount,

		// 下发统计
		OrderId:    data.OrderID,
		Platform:   int32(platform),
		PayStatus:  int32(data.PayStatus),
		OutTradeNo: data.PublishSchedule.OutTradeNo,
	}

	// 材料
	for _, m := range data.Materials {
		res.Data.Materials = append(res.Data.Materials, &advertisingc.SPublishScheduleDetailOrderInfoRsp_Data_Materials{
			MaterialId:             m.MaterialID,
			FilePath:               m.FilePath,
			Name:                   m.Name,
			Type:                   int32(m.Type),
			Duration:               m.Duration,
			RepeatTimes:            m.RepeatTimes,
			PlayType:               m.PlayType,
			RegularInterval:        m.RegularInterval,
			DeviceHasMaterialCount: int32(m.DeviceHasMaterialCount),
			DeviceHasMaterial:      m.DeviceHasMaterial,
		})
	}

	return res, nil
}

// 投放计划审核记录列表
func (s *Server) ScheduleAuditLogListOrderInfo(ctx context.Context, req *advertisingc.SPublishScheduleAuditLogListOrderInfoReq) (*advertisingc.SPublishScheduleAuditLogListOrderInfoRsp, error) {
	db := mysql.NewDB()
	var res = &advertisingc.SPublishScheduleAuditLogListOrderInfoRsp{}
	tx := db.Table(models.PublishScheduleAuditLog{}.TableName() + " as log").
		Joins("join " + models.PublishSchedule{}.TableName() + " as ps on ps.id = log.schedule_id").
		Where("ps.deleted_at = 0")

	// 计划名称
	if req.Name != "" {
		tx = tx.Where("ps.name like ?", "%"+strings.TrimSpace(req.Name)+"%")
	}

	// 投放位置
	if req.Position != 0 {
		tx = tx.Where("ps.position = ?", req.Position)
	}

	// 状态
	if req.Status != 0 {
		tx = tx.Where("ps.status = ?", req.Status)
	}

	// 开始时间和结束时间
	if req.StartTime != 0 && req.EndTime != 0 {
		tx = tx.Where("(ps.start_time <= ? AND ps.end_time >= ?) OR (ps.start_time >= ? AND ps.end_time <= ?) OR (ps.start_time <= ? AND ps.end_time >= ?)",
			req.StartTime, req.StartTime, req.StartTime, req.EndTime, req.EndTime, req.EndTime)
	}

	// 创建时间范围
	if req.CreatedStartTime != 0 && req.CreatedEndTime != 0 {
		tx = tx.Where("ps.created_at >= ? AND ps.created_at <= ?", req.CreatedStartTime, req.CreatedEndTime)
	}

	// 商圈id
	if req.LocationId != "" {
		tx = tx.Where("ps.location_id like ?", "%"+req.LocationId+"%")
	}

	// 县区id
	if req.DistrictId != "" {
		tx = tx.Where("ps.district_id like ?", "%"+req.DistrictId+"%")
	}

	// 商户id
	if req.MerchantId != "" && req.MerchantId != "1" {
		tx = tx.Where("ps.merchant_id = ?", req.MerchantId)
	}

	// 商户路径
	if req.MerchantPath != "" {
		tx = tx.Where("ps.merchant_id like ?", req.MerchantPath+"%")
	}

	// 创建平台
	if req.Platform == 1 {
		tx = tx.Where("(ps.order_id IS NULL OR ps.order_id = '')")
	} else if req.Platform == 2 {
		tx = tx.Where("ps.order_id IS NOT NULL AND ps.order_id != ''")
	}

	// 金额阈值
	if req.AmountThresh > 0 {
		tx = tx.Where("ps.pay_amount >= ?", req.AmountThresh)
	}

	// 订单相关字段（这些字段存储在 PublishSchedule 表中）
	if req.CustomName != "" {
		tx = tx.Where("ps.custom_name like ?", "%"+req.CustomName+"%")
	}

	if req.PhoneNumber != "" {
		tx = tx.Where("ps.phone_number like ?", "%"+req.PhoneNumber+"%")
	}

	if req.OutTradeNo != "" {
		tx = tx.Where("ps.out_trade_no = ?", req.OutTradeNo)
	}

	// 审核状态
	if req.AuditStatus != 0 {
		tx = tx.Where("log.audit_status = ?", int32(req.AuditStatus))
	}

	// 投放设备（需要先通过设备表查询出对应的 schedule_id）
	var scheduleIDListByDevice []string
	if req.Devices != "" {
		deviceList, _, _ := dao.PublishScheduleDevice{}.List(ctx, db, "", "", req.Devices, 0, 0, 0, true, 0, 0)
		for _, v := range deviceList {
			if !lo.Contains(scheduleIDListByDevice, v.ScheduleID) {
				scheduleIDListByDevice = append(scheduleIDListByDevice, v.ScheduleID)
			}
		}
		if len(scheduleIDListByDevice) == 0 {
			// 如果设备找不到计划，返回空
			res.Data = &advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data{
				Count: 0,
				List:  []*advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList{},
			}
			return res, nil
		}
		tx = tx.Where("ps.id IN (?)", scheduleIDListByDevice)
	}
	var result = []struct {
		models.PublishSchedule
		AuditMerchantName string `json:"audit_merchant_name" gorm:"column:audit_merchant_name"`
		AuditUsername     string `json:"audit_username" gorm:"column:audit_username"`
		AuditStatus       int    `json:"audit_status" gorm:"column:audit_status"`
		AuditAt           int64  `json:"audit_at" gorm:"column:audit_at"`
	}{}
	res.Data = &advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data{}
	
	// 先计算总数（在分页之前）
	var totalCount int64
	tx.Count(&totalCount)
	
	// 分页查询
	helper.Gorm{}.Paginate(tx, int(req.Page), int(req.Limit)).
		Select("ps.*, log.audit_merchant_name, log.audit_username, log.audit_status, log.audit_at").
		Order("log.audit_at desc").
		Find(&result)
	var scheduleIDList []string
	for _, v := range result {
		scheduleIDList = append(scheduleIDList, v.ID)
	}
	// 投放素材
	ScheduleMaterialList, _ := dao.PublishScheduleMaterial{}.MaterialList(ctx, db, strings.Join(scheduleIDList, ","))
	var ScheduleMaterialMap = make(map[string][]*advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList_Materials)
	for _, v := range ScheduleMaterialList {

		ScheduleMaterialMap[v.ScheduleID] = append(ScheduleMaterialMap[v.ScheduleID], &advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList_Materials{
			MaterialId:      v.MaterialID,
			FilePath:        v.FilePath,
			Name:            v.Name,
			Type:            int32(v.Type),
			Duration:        v.Duration,
			PlayType:        int32(v.PlayType),
			RegularInterval: int32(v.RegularInterval),
		})
	}
	// 投放设备
	ScheduleDeviceCount := dao.PublishScheduleDevice{}.ScheduleRobotCount(ctx, db, strings.Join(scheduleIDList, ","))
	var ScheduleDeviceCountMap = make(map[string]int64)
	for _, v := range ScheduleDeviceCount {
		ScheduleDeviceCountMap[v.ScheduleID] = v.DeviceCount
	}

	//投放设备[true 不包含待删除]
	ScheduleDeviceList, _, _ := dao.PublishScheduleDevice{}.List(ctx, db, "", strings.Join(scheduleIDList, ","), "", 0, 0, 0, true, 0, 0)
	var ScheduleDeviceMap = make(map[string][]string)
	for _, v := range ScheduleDeviceList {
		if !lo.Contains(ScheduleDeviceMap[v.ScheduleID], v.RobotName) { // 设备去重
			ScheduleDeviceMap[v.ScheduleID] = append(ScheduleDeviceMap[v.ScheduleID], v.RobotName)
		}
	}

	client, err := client.GetMiniAppClient()
	if err != nil {
		return nil, nil
	}

	// 用于存储最终结果，根据支付状态过滤
	var finalResult []*advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList

	for _, v := range result {
		var deviceCount int64
		if _, ok := ScheduleDeviceCountMap[v.ID]; ok {
			deviceCount = ScheduleDeviceCountMap[v.ID]
		}

		devices, _, _ := dao.PublishScheduleDevicePlaylist{}.List(ctx, db, v.ID, "", 0, 0, 99999)

		var mvvs []*advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList_Materials
		for _, mv := range ScheduleMaterialMap[v.ID] {

			mvv := advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList_Materials{
				MaterialId:      mv.MaterialId,
				FilePath:        mv.FilePath,
				Name:            mv.Name,
				Type:            int32(mv.Type),
				Duration:        mv.Duration,
				PlayType:        int32(mv.PlayType),
				RegularInterval: int32(mv.RegularInterval),
			}

			for dk, _ := range devices {
				if devices[dk].MaterialID == mvv.MaterialId {
					mvv.DeviceHasMaterialCount += 1
					mvv.DeviceHasMaterial += devices[dk].RobotName
					if dk < len(devices)-1 {
						mvv.DeviceHasMaterial += ","
					}
				}
			}
			mvvs = append(mvvs, &mvv)
		}
		var Orientation int
		if v.PublishType == 1 || v.PublishType == 3 { // 刊例 【1刊例单素材，3刊例多素材】
			Orientation = 0 // "-"
		} else if len(strings.Split(v.Gender, ",")) == len(define.GenderMap) && len(strings.Split(v.Age, ",")) == len(define.AgeMap) && len(strings.Split(v.Tag, ",")) == len(define.TagMap) {
			Orientation = 1 // 默认
		} else {
			Orientation = 2 // 定向
		}
		item := &advertisingc.SPublishScheduleAuditLogListOrderInfoRsp_Data_PublishScheduleAuditLogList{
			Id:             v.ID,
			Name:           v.Name,
			Position:       int32(v.Position),
			StartTime:      v.StartTime,
			EndTime:        v.EndTime,
			Duration:       v.Duration,
			Details:        v.Details,
			Status:         int32(v.Status),
			DistrictId:     v.DistrictID,
			LocationId:     v.LocationID,
			MerchantId:     v.MerchantID,
			MerchantName:   v.MerchantName,
			CreateUser:     v.CreateUser,
			CreateUsername: v.CreateUserName,
			CreatedAt:      v.CreatedAt,
			DeletedAt:      v.DeletedAt,
			DeviceCount:    deviceCount,
			Orientation:    int32(Orientation),
			PublishType:    int32(v.PublishType),
			// Devices:        v.Devices,
			Materials:   mvvs,
			DetailsShow: int32(v.DetailsShow),
			// DeviceLocation: v.DeviceLocation,
			PublishCount: v.PublishCount,
			Gender:       v.Gender,
			Age:          v.Age,
			Tag:          v.Tag,

			AuditMerchantName: v.AuditMerchantName,
			AuditUsername:     v.AuditUsername,
			AuditAt:           v.AuditAt,
			AuditStatus:       int32(v.AuditStatus),
			Platform:          1,
		}

		var params mini_app.GetAdvertisementOrderReq
		params.Id = v.OrderID
		resp, err1 := client.GetAdvertisementOrder(ctx, &params)
		if err1 != nil {
			err = err1
		}
		// 将resp的内容填写到data里
		if resp != nil && resp.Data != nil {

			// 订单扩展信息
			item.CustomName = resp.Data.CustomName
			item.PhoneNumber = resp.Data.PhoneNumber
			item.DeviceIds = resp.Data.DeviceIds
			item.StartAt = resp.Data.StartAt
			item.EndAt = resp.Data.EndAt
			item.Remark = resp.Data.Remark
			item.Openid = resp.Data.Openid
			item.AdvertisementId = resp.Data.AdvertisementId
			item.PayAmount = resp.Data.PayAmount
			item.PaidAmount = resp.Data.PaidAmount
			item.PaidId = resp.Data.PaidId
			item.DiscountAmount = resp.Data.DiscountAmount

			// 下发统计
			item.OrderId = resp.Data.Id
			item.Platform = 2
			item.PayStatus = int32(resp.Data.Status)
		} else {
			// 如果没有订单信息，使用 PublishSchedule 表中的字段
			item.CustomName = v.CustomName
			item.PhoneNumber = v.PhoneNumber
			item.OutTradeNo = v.OutTradeNo
			item.PayAmount = v.PayAmount
			item.PaidAmount = v.PaidAmount
			item.DiscountAmount = v.DiscountAmount
			item.OrderId = v.OrderID
			// 支付状态需要从订单获取，如果没有订单信息，则跳过支付状态过滤
		}

		if _, ok := ScheduleDeviceMap[v.ID]; ok {
			item.Devices = ScheduleDeviceMap[v.ID]
		}

		// 根据支付状态过滤
		if req.PayStatus > 0 {
			// 如果有支付状态条件，只添加匹配的记录
			// 注意：支付状态需要从订单信息中获取，如果没有订单信息则跳过
			if item.PayStatus > 0 && item.PayStatus == int32(req.PayStatus) {
				finalResult = append(finalResult, item)
			}
		} else {
			// 没有支付状态条件，直接添加
			finalResult = append(finalResult, item)
		}
	}

	// 设置结果
	// 注意：如果设置了支付状态过滤，实际返回的数量可能小于 totalCount
	// 但由于支付状态信息需要从订单服务获取，无法在数据库层面精确计算
	res.Data.Count = totalCount
	res.Data.List = finalResult

	return res, nil
}
